package org.chuanyang.mm.db;

import org.chuanyang.mm.db.MetaData.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	private volatile static DBHelper dbHelper;
	private static String name = DB.DBNAME;
	private static int version = DB.VERSION;
	private static String[] table_sql = { DB.CATEGORY_DEFAULT_SQL,
			DB.INCOMING_DEFAULT_SQL, DB.OUTLAY_DEFAULT_SQL };
	private static CursorFactory factory = null;

	private DBHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	public static DBHelper getInstance(Context context) {
		if (dbHelper == null) {
			synchronized (DBHelper.class) {
				if (dbHelper == null) {
					dbHelper = new DBHelper(context, name, factory, version);
				}
			}
		}
		return dbHelper;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		System.out.println("------------create db: ok------------");
		execSQLs(db);
		initCategoryTable(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}

	private void execSQLs(SQLiteDatabase db) {

		for (int i = 0; i < table_sql.length; i++) {
			db.execSQL(table_sql[i]);
			System.out.println("------------create table_sql[" + i
					+ "]:OK------------");
		}

	}

	private void initCategoryTable(SQLiteDatabase db) {
		System.out.println("------------initCategoryTable begin------------");

		ContentValues values;

		for (int i = 0; i < DB.INCOMING_CATEGORY_DEFAULT.length; i++) {
			values = new ContentValues();
			values.put(DB.TABLE[DB.INCOMING], DB.INCOMING_CATEGORY_DEFAULT[i]);
			db.insert(DB.TABLE[DB.CATEGORY], null, values);
		}

		for (int i = 0; i < DB.OUTLAY_CATEGORY_DEFAULT.length; i++) {
			values = new ContentValues();
			values.put(DB.TABLE[DB.OUTLAY], DB.OUTLAY_CATEGORY_DEFAULT[i]);
			db.insert(DB.TABLE[DB.CATEGORY], null, values);
		}

		System.out.println("------------initCategoryTable ok------------");
	}
}
